package com.biubiushop.util.shouqianba;


import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSONObject;
import com.biubiushop.constant.ShouQianbaConstant;
import org.springframework.util.DigestUtils;

import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Random;
import java.util.Set;

public class ShouQianBaUtil {
    private final static String CHARSET_UTF8 = "utf8";

    private static final String api_domain = ShouQianbaConstant.api_domain;

    //    private static String terminal_sn = ShouQianbaConstant.terminal_sn;
    private static String terminal_sn = " ";

    /**
     * 计算字符串的MD5值
     *
     * @param signStr:签名字符串
     * @return
     */
    public static String getSign(String signStr) {
        return DigestUtil.md5Hex(signStr, CHARSET_UTF8);
    }

    public static String getClient_Sn(int codeLenth) {
        while (true) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < codeLenth; i++) {
                if (i == 0) {
                    sb.append(new Random().nextInt(9) + 1); // first field will not start with 0.
                } else {
                    sb.append(new Random().nextInt(10));
                }
            }

            return sb.toString();
        }
    }

    /**
     * 终端激活
     *
     * @param code:激活码
     * @param vendor_sn:服务商序列号
     * @param vendor_key:服务商密钥
     * @param appid:应用编号
     * @return {terminal_sn:"$终端号",terminal_key:"$终端密钥"}
     */
    public static JSONObject activate(String vendor_sn, String vendor_key, String appid, String code) {
        String url = api_domain + "/terminal/activate";
        JSONObject params = new JSONObject();
        try {
            params.put("appid","");                                   //appid，必填
            params.put("code", "");                                     //激活码，必填
            params.put("device_id", " ");                     //客户方收银终端序列号，需保证同一appid下唯一，必填。为方便识别，建议格式为“品牌名+门店编号+‘POS’+POS编号“
            params.put("name", " ");                                 //客户方终端名称，必填
//            params.put("client_sn", "POS01");                             //客户方终端编号，一般客户方或系统给收银终端的编号，必填
//            params.put("os_info", "Mac OS");
//            params.put("sdk_version", "Java SDK v1.0");     //SDK版本

            return getJsonObject(vendor_sn, vendor_key, url, params);
        } catch (Exception e) {
            return null;
        }
    }

    private static JSONObject getJsonObject(String sn, String key, String url, JSONObject params) throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        String sign = getSign(params.toString() + key);
        String result = HttpUtil.httpPost(url, params.toString(), sign, sn);
        JSONObject retObj = JSONObject.parseObject(result);
        String resCode = retObj.get("result_code").toString();
        if (!resCode.equals("200")) {
            return null;
        }
        String responseStr = retObj.get("biz_response").toString();
        JSONObject terminal = JSONObject.parseObject(responseStr);
        if (terminal.get("terminal_sn") == null || terminal.get("terminal_key") == null) {
            return null;
        }
        return terminal;
    }

    /**
     * 终端签到
     *
     * @param terminal_sn:终端号
     * @param terminal_key:终端密钥
     * @return {terminal_sn:"$终端号",terminal_key:"$终端密钥"}
     */
    public static JSONObject checkin(String terminal_sn, String terminal_key) {
        String url = api_domain + "/terminal/checkin";
        JSONObject params = new JSONObject();
        try {
            params.put("terminal_sn", terminal_sn);
            params.put("device_id", "GZBBWL-001");
//            params.put("os_info", "Mac OS");
//            params.put("sdk_version", "Java SDK v1.0");
            return getJsonObject(terminal_sn, terminal_key, url, params);
        } catch (Exception e) {
            return null;
        }
    }


    /**
     * 付款
     *
     * @return
     */
    public static String pay(JSONObject params, String terminal_key) {
        String url = ShouQianbaConstant.pay_domain + "/upay/v2/pay";
        try {
            String sign = getSign(params.toJSONString() + terminal_key);
            String result = HttpUtil.httpPost(url, params.toString(), sign, terminal_sn);
            return result;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 退款
     *
     * @param terminal_sn:终端号
     * @param terminal_key:终端密钥
     * @return
     */
    public static String refund(String terminal_sn, String terminal_key) {
        String url = api_domain + "/upay/v2/refund";
        JSONObject params = new JSONObject();
        try {
            params.put("terminal_sn", terminal_sn);            //收钱吧终端ID
            params.put("sn", " ");              //收钱吧系统内部唯一订单号
            params.put("client_sn", " ");   //商户系统订单号,必须在商户系统内唯一；且长度不超过64字节
            params.put("refund_amount", "1000");               //退款金额
            params.put("refund_request_no", "23030349");          //商户退款所需序列号,表明是第几次退款
            params.put("operator", "kay");                      //门店操作员

            String sign = getSign(params.toString() + terminal_key);
            String result = HttpUtil.httpPost(url, params.toString(), sign, terminal_sn);

            return result;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 查询
     *
     * @param params:查询参数
     * @param terminal_key:终端密钥
     * @return
     */
    public static String query(JSONObject params, String terminal_key) {
        String url = api_domain + "/upay/v2/query";
        try {
            String sign = getSign(params.toString() + terminal_key);
            String result = HttpUtil.httpPost(url, params.toString(), sign, terminal_sn);
            return result;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 自动撤单
     *
     * @param params:查询参数
     * @param terminal_key:终端密钥
     * @return
     */
    public static String cancel(JSONObject params, String terminal_key) {
        String url = api_domain + "/upay/v2/cancel";
        try {
            String sign = getSign(params.toString() + terminal_key);
            String result = HttpUtil.httpPost(url, params.toString(), sign, terminal_sn);

            return result;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 预下单
     *
     * @return
     */
    public static String precreate(JSONObject params, String terminal_key) {
        String url = api_domain + "/upay/v2/precreate";
        try {
            String sign = getSign(params.toString() + terminal_key);
            String result = HttpUtil.httpPost(url, params.toString(), sign, terminal_sn);
            return result;
        } catch (Exception e) {
            return null;
        }
    }

    public static void main(String[] args) throws Exception {

//        //激活终端
//        String code = " ";
//        JSONObject jsonObject = activate(ShouQianbaConstant.vendor_sn,ShouQianbaConstant.vendor_key,ShouQianbaConstant.appid,code);
//        System.out.println(jsonObject);

        //终端签到
        JSONObject json = checkin(" "," ");
        System.out.println(json);



    }

    private static String getShouQianBaSign(JSONObject jsonObject, String terminal_key) {
        // 根据ASCII字典序排序
        Set<String> set = jsonObject.keySet();
        LinkedList<String> list = new LinkedList<>(set);
        Collections.sort(list);
        // 拼接参数
        StringBuilder sb = new StringBuilder();
        for (String key : list) {
            sb.append(key + "=" + jsonObject.get(key) + "&");
        }
        // 拼接api密钥
        String stringSign = sb + "key=" + terminal_key;

        String sign = DigestUtils.md5DigestAsHex(stringSign.getBytes()).toUpperCase();

        String url = stringSign + "&sign=" + sign;

        return url;
    }

}
